package org.example.netty.httpserver;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.lang.ref.WeakReference;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class HttpEchoHandler extends ChannelInboundHandlerAdapter {

    private static final AtomicInteger channelReadCounter = new AtomicInteger(0);

    private static final AtomicInteger channelReadCompleteCounter = new AtomicInteger(0);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            log.info("HttpEchoHandler channelRead");
            // 释放内存
            ((FullHttpRequest)msg).release();
            // 消息超过高水位，isWritable会返回false
            if (ctx.channel().isActive() && ctx.channel().isWritable()) {
                ByteBuf byteBuf = Unpooled.copiedBuffer("hello netty".getBytes(StandardCharsets.UTF_8));

                FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);
                response.headers().add(HttpHeaderNames.CONTENT_TYPE, "text/plain;");
                response.headers().add(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());
                // 传递给下一级由flush处理
                super.channelRead(ctx, response);
            }
        } else {
            super.channelRead(ctx, msg);
        }
        log.info("channelReadCounter = {}", channelReadCounter.getAndIncrement());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
        log.info("channelReadCompleteCounter = {}", channelReadCounter.getAndIncrement());
    }

    /**
     * 超过高水位时触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        super.channelWritabilityChanged(ctx);
    }
}
